<template>
    <div class="tc-toptitle">
      <div class="toptitle-title" @click="isShowNav">
        <i class="iconfont iconshouqi" v-if="!this.isCollapse"></i>
        <i class="iconfont iconzhankai" v-if="this.isCollapse"></i>
      </div>
      <div class="toptotle-avatar">
          <div class="block">
            <div class="search mr-20" v-if="isSystem !== 1 && showSelect" >
              <el-select v-model="params.partnerId" placeholder="请选择" @change="partnerChange">
                <el-option
                  v-for="item in partnerOptions"
                  :key="item.value"
                  :label="item.partnerName"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="tongzhi"><i class="iconfont iconsearch mr-15"></i></div>
            <div class="fenge"><i class="iconfont iconremind mr-15"></i></div>
            <el-avatar v-if="$store.state.userInfo.userHeadImg" :size="22" :src="circleUrl"></el-avatar>
            <el-avatar v-if="!$store.state.userInfo.userHeadImg" :size="22" src="./../../../static/img/headImg.png"></el-avatar>
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link">
                {{$store.state.userInfo.userRealName}}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="changepwd"><i class="iconfont icon-V"></i>修改密码</el-dropdown-item>
                <!-- <el-dropdown-item><i class="iconfont icon-yonghu"></i>个人信息</el-dropdown-item> -->
                <el-dropdown-item command="logOut"><i class="iconfont icon-tuichu"></i>退出系统</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
      </div>

      <!-- 修改密码 -->
      <el-dialog class="dialog-form" title="修改密码" :visible.sync="showChangePwd" :close-on-click-modal="false" :before-close="beforeClose">
        <el-form :rules="rules" ref="fromData" :model="fromData">
          <el-form-item label="旧密码" prop="userOldPwd" :label-width="formLabelWidth">
            <el-input type="password" v-model="fromData.userOldPwd"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="userPwd" :label-width="formLabelWidth">
            <el-input type="password" v-model="fromData.userPwd" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="password" :label-width="formLabelWidth">
            <el-input type="password" v-model="fromData.password" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showChangePwd = false">取 消</el-button>
          <el-button type="primary" :loading="isBtnLoading" @click="submitForm('fromData')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { getTIme } from '@/utils/util';
import { mapState,mapMutations } from 'vuex';
import { logOut, updateUserPwd } from '@/axios/user/user';
import { findPartnerList} from '@/axios/user/organization';
import { getRoleMenuTree, getRouters } from '@/axios/user/menu';
import { getUserInfo } from '@/axios/user/user';
import md5 from 'js-md5';

export default {
  name: 'toptitle',
  data () {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else if (reg.test(value)) {
        callback(new Error('请输入6-12数字, 字符, 或组合'));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.fromData.userPwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
        circleUrl: this.$store.state.userInfo.userHeadImg,
        params: {
          partnerId: ''
        },
        fromData: {
          password: '',
          userOldPwd: '',
          userPwd: '',
          userId: ''
        },
        showSelect: true,
        showChangePwd: false,
        isBtnLoading: false,
        formLabelWidth: '',
        partnerOptions: [],
        rules: {
        userPwd: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass2, trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        userOldPwd: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ]
        }
    }
  },
  components: {

  },
  created(){
    this.init()
  },
  computed:{
    ...mapState([
      'isCollapse',
      'isSystem',
      'partnerData',
      'userInfo',
      'currentData'
    ])
  },
  watch: {
    '$route': {
      immediate: true,
      handler (v) {
        if (v) {
          if (v.name === '功能权限' || v.name === '司机档案') {
            if (this.partnerOptions.length > 0 && this.isSystem === 1) {
              this.SAVE_PARTNERDATA(this.partnerOptions[0])
            }
          }
        }
      }
    }
  },
  methods:{
    ...mapMutations([
      'SAVE_ISCOLLAPSE',
      'SAVE_TOKEN',
      'SAVE_PARTNERDATA',
      'SAVE_CURRENTDATA',
      'SAVE_MENUDATA',
      'SAVE_ISSYSTEM',
      'SAVE_EDITABLETABS',
      'SAVE_EDITABLETABSVALUE'
    ]),
    /**
     * @method 初始化
     */
    async init(){
      //设置当前时间
      var self = this
      this.SAVE_ISCOLLAPSE(false)
      findPartnerList().then(res => {
        if (res.code === 200) {
          if (res.data.length > 0) {
            self.partnerOptions = res.data
            if (!self.currentData) {
              self.SAVE_PARTNERDATA(self.partnerOptions[0])
              self.SAVE_CURRENTDATA(self.partnerOptions[0])
              self.params.partnerId = self.partnerOptions[0].id
            } else {
              self.params.partnerId = self.currentData.id
            }
            if (self.partnerOptions.length > 0 && self.isSystem === 1) {
              // 非平台账号
            }
            if (res.data.length === 1) {
              self.showSelect = false
            }
          }
          self.getMenuList()
        }
      })
    },
    getMenuList() {
      getRoleMenuTree({
        userId: this.userInfo.userId,
        partnerId: this.isSystem === 1 ? 1 : this.currentData.id,
      }).then(res => {
        if (res.code === 200) {
          this.SAVE_MENUDATA(res.data)
        }
      })
    },
    /**
     * @method 下拉菜单触发
     */
    handleCommand(command) {
      if (command === 'logOut') {
        logOut().then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.msg
            })
            this.SAVE_TOKEN('')
            localStorage.removeItem("vuex");
            localStorage.removeItem("user");
            sessionStorage.clear();
            this.$router.push('/login')
            //想清空vuex中的数据，让页面重新加载就行了
            window.location.reload()
          }
        })
      } else if (command === 'changepwd') {
        this.showChangePwd = true
      }
    },
    isShowNav() {
      this.SAVE_ISCOLLAPSE(!this.isCollapse)
    },
    partnerChange(id) {
      this.partnerOptions.forEach((v) => {
        if (v.id === id) {
          this.SAVE_PARTNERDATA(v)
          this.SAVE_CURRENTDATA(v)
        }
      })
      getUserInfo().then(res => {
        if (res.code === 200 ) {
            this.$store.state.userInfo =  {
                // userHeadImg: res.user.phonenumber,
                userRealName: res.data.user.nickName,
                userId: res.data.user.userId,
                userPhone: res.data.user.phonenumber
            }
            if ( res.data.user.userType === '00' ) {
                this.SAVE_ISSYSTEM(1)
            } else {
                this.SAVE_ISSYSTEM(2)
            }
        }
      })
      this.SAVE_EDITABLETABSVALUE('')
      this.SAVE_EDITABLETABS('')
      this.getMenuList()
      this.$router.push('/index')
    },
    beforeClose() {
      this.fromData = {
        password: '',
        userOldPwd: '',
        userPwd: '',
        userId: ''
      }
      this.showChangePwd = false
    },
    submitForm(formName) {
      var then = this
      then.$refs[formName].validate((valid) => {
        if (valid) {
          this.changepwd()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    changepwd() {
      var then = this
      const data = JSON.parse(JSON.stringify(then.fromData))
      var jsonData = {
        oldPassword: data.userOldPwd,
        newPassword: data.userPwd
      }
       this.$confirm('是否确认修改密码?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateUserPwd(jsonData).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.showChangePwd = false
              logOut().then(res => {
                if (res.code === 200) {
                  this.SAVE_TOKEN('')
                  localStorage.removeItem("vuex");
                  localStorage.removeItem("user");
                  this.$router.push({
                    path:'/login'
                  })
                }
              })
            }
          })
        }).catch(() => {})
    }
  }
};
</script>

<style lang="scss">
@import '../../style/mixin';
@import "./topTitle.scss";
</style>